<?php
require 'vendor/autoload.php';

use React\EventLoop\Factory;
use React\Socket\Server as SocketServer;

$loop = Factory::create();

// Create a new socket server that listens on all available network interfaces (0.0.0.0)
$socketServer = new SocketServer('0.0.0.0:8080', $loop);

echo "TCP Server listening on 0.0.0.0:8080\n";

$socketServer->on('connection', function ($connection) {
    echo "New client connected.\n";

    $connection->on('data', function ($data) use ($connection) {
        $message = $data->toString();
        echo "Received message: $message\n";

        // Respond back to the client
        $connection->write("Server received: $message");

        // Close the connection after sending the response
        $connection->end();
    });

    $connection->on('end', function () {
        echo "Client disconnected.\n";
    });
});

$loop->run();
?>
